package com.jic.interaction.JDVOP.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jic.interaction.JDVOP.common.utils.JdVopHttpUtil;
import com.jic.interaction.JDVOP.mapper.MProductBrandMapper;
import com.jic.interaction.JDVOP.mapper.MProductMediaMapper;
import com.jic.interaction.JDVOP.mapper.ProductMapper;
import com.jic.interaction.JDVOP.model.entity.JDProduct;
import com.jic.interaction.JDVOP.model.entity.MProductBrand;
import com.jic.interaction.JDVOP.model.entity.Product;
import com.jic.interaction.JDVOP.model.entity.MProductMedia;
import com.jic.interaction.JDVOP.model.vo.request.*;
import com.jic.interaction.JDVOP.model.vo.response.*;
import com.jic.interaction.JDVOP.service.ProductService;
import com.jic.product.rest.response.ProductCategoryRestResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
public class ProductServiceImpl implements ProductService {


    @Resource
    private ProductMapper productMapper;

    @Resource
    private MProductBrandMapper productBrandMapper;

    @Resource
    private MProductMediaMapper productMediaMapper;


    @Value("${route.JDVOP}")
    private String url;

    /**
     *
     *
     * @description:   查询商品池编号
     * @return: String
     * @author: fengrui
     * @time: 2020/11/15 17:02
     */
    @Override
    public List<ProductResultResponse> queryCommodityPools(String token) throws Exception {
        log.info("查询商品池编号开始，请求参数："+token);
        Map<String, String> map = new HashMap<>();
        map.put("token",token);
        String value = JdVopHttpUtil.doRequestPost(url + "/api/product/getPageNum", map);

        JSONObject jsonObject = JSONObject.parseObject(value);
        List<ProductResultResponse> list = null;
        if (jsonObject.containsKey("result")) {
            // 获取到key为shoppingCartItemList的值
            if (jsonObject.getJSONArray("result")!=null){
                list = jsonObject.getJSONArray("result").toJavaList(ProductResultResponse.class);
            }
        }
        Product product = new Product();
        log.info("查询商品池编号结束，获取返回值："+jsonObject.toString());
        for (int i = 0; i < list.size(); i++){
            product.setThirdProductCode(list.get(i).getPage_num());
            product.setChineseName(list.get(i).getName());
            productMapper.toinsert(product);
        }

        return list;
    }

    /**
     *
     *
     * @description: 查询池内商品编号
     * @return: String
     * @author: fengrui
     * @time: 2020/11/16 10:32
     *  接口报错  ：    执行请求完毕：{"success":false,"resultMessage":"服务异常，请稍后重试","resultCode":"5001"}
     */
    @Override
    public List<ProductCodeResponse> queryProductCode(ProductResultRequest request) throws Exception {
        log.info("查询池内商品编号开始，请求参数："+request.toString());
        JSONObject jsonObject = JSONObject.parseObject(JdVopHttpUtil.doRequestPost(url + "/api/product/getSkuByPage", JSON.parseObject(JSON.toJSONString(request), Map.class)));
        List<ProductCodeResponse> list = null;
        if (jsonObject.containsKey("result")){
            if (jsonObject.getJSONArray("result")!=null){
                list = jsonObject.getJSONArray("result").toJavaList(ProductCodeResponse.class);
            }
        }
        log.info("查询池内商品编号结束，获取返回值："+jsonObject.toString());
        return list;
    }

    /**
     *
     *
     * @description: 获取商品详情
     * @return:  String
     * @author: fengrui
     * @time: 2020/11/16 10:31
     */  
    @Override
    public MatterProductRequest getProductDetails(ProductDetailsRequest request) throws Exception {
        log.info("获取商品详情开始，参数"+request.toString());
        String value = JdVopHttpUtil.doRequestPost(this.url + "api/product/getDetail", JSON.parseObject(JSON.toJSONString(request), Map.class));
//        JSONObject jsonObject = JSONObject.parseObject(value);
        MatterProductRequest matter = null;
        MProductBrand brand = new MProductBrand();
        JDProduct product = new JDProduct();
        if(StringUtils.isNotEmpty(value) && JSON.parseObject(value).getString("resultCode").equals("0000")) {
            List<Map> resData = JSONArray.parseArray(JSON.parseObject(value).getJSONObject("result").getString(request.getSku()), Map.class);
            for (Map resDatum : resData) {
                Map a = resDatum;
                BeanUtils.populate(matter ,a);
//                list.add(matter);
                product.setChineseName(matter.getName());
                product.setThirdProductCode(matter.getSku());
                BigDecimal bigDecimal = new BigDecimal(matter.getWeight());
                product.setGrossWeight(bigDecimal);
                product.setPlaceOriginName(matter.getProductArea());
                product.setCanSale(Integer.parseInt(matter.getState()));

                brand.setId(Long.valueOf(matter.getSku()));
                brand.setName(matter.getBrandName());
                productBrandMapper.insert(brand);
                productMapper.insert(product);
            }
        }

//        if (jsonObject.containsKey("result")){
//            if (jsonObject.getJSONArray("result")!=null){
//                matter = jsonObject.getJSONArray("result").toJavaObject(MatterProductRequest.class);
//            }
//        }
//        product.setChineseName(matter.getName());
//        product.setThirdProductCode(matter.getSku());
//        BigDecimal bigDecimal = new BigDecimal(matter.getWeight());
//        product.setGrossWeight(bigDecimal);
//        product.setPlaceOriginName(matter.getProductArea());
//        product.setCanSale(Integer.parseInt(matter.getState()));
//
//        brand.setId(Long.valueOf(matter.getSku()));
//        brand.setName(matter.getBrandName());
//        productBrandMapper.insert(brand);
//        productMapper.insert(product);
        log.info("获取商品详情结束，返回值："+value.toString());
        return matter;
    }

    @Override
    public ProductImageResponse getProductSkuImage(ProductImageRequest request) throws Exception {
        log.info("获取商品图片，请求参数："+request.toString());
        String res = JdVopHttpUtil.doRequestPost(this.url + "api/product/skuImage", JSON.parseObject(JSON.toJSONString(request), Map.class));
        MProductMedia productMedia = new MProductMedia();
        ProductImageResponse productImageResponse = new ProductImageResponse();
        ArrayList<ProductImageResponse> list = new ArrayList<>();
        if(StringUtils.isNotEmpty(res) && JSON.parseObject(res).getString("resultCode").equals("0000")){
            List<Map> resData = JSONArray.parseArray(JSON.parseObject(res).getJSONObject("result").getString(request.getSku()),Map.class);
            System.out.println(resData);
            for (Map resDatum : resData) {
                Map a = resDatum;
                BeanUtils.populate(productImageResponse ,a);
                list.add(productImageResponse);
                productMedia.setProductId(Long.valueOf(request.getSku()));
                productMedia.setIsMainPicture(productImageResponse.getIsPrimary());
                productMedia.setPictureUrl(productImageResponse.getPath());
                productMediaMapper.insert(productMedia);
            }
        }




       /* ProductImageResponse value = null;
        if (jsonObject.containsKey("result")){  //判断 jsonObject 中是否存在result这个key
            if (jsonObject.getJSONArray("result")!=null){
                value = jsonObject.getJSONArray("result").toJavaObject(ProductImageResponse.class);
            }
        }
        log.info("获取商品图片结束，返回值"+jsonObject.toString());

        productMedia.setProductId(value.getSkuId());
        productMedia.setIsMainPicture(value.getIsPrimary());
        productMedia.setPictureUrl(value.getPath());
        productMedia.setType(0);
        System.out.println("________________________________________________________");
        productMediaMapper.insertSelective(productMedia);*/

        return null;
    }

    @Override
    public List<ProductStatusResponse> getProductStatus(ProductStatusRequesr request) throws Exception {
        log.info("获取商品状态，请求参数："+request.toString());
        JSONObject jsonObject = JSON.parseObject(JdVopHttpUtil.doRequestPost(this.url + "api/product/skuState", JSON.parseObject(JSON.
                toJSONString(request), Map.class)));
        List<ProductStatusResponse> value = null;
        if (jsonObject.containsKey("result")) {
            if (jsonObject.getJSONArray("result")!=null){
                value = jsonObject.getJSONArray("result").toJavaList(ProductStatusResponse.class);
            }
        }
        log.info("获取商品状态结束，返回值"+jsonObject.toString());
        return value;
    }

    @Override
    public List<ProductCheckResponse> availableSex(ProductCheckRequest request) throws Exception {
        log.info("获取商品可售性，请求参数："+request.toString());
        JSONObject jsonObject = JSON.parseObject(JdVopHttpUtil.doRequestPost(this.url + "api/product/chech", JSON.parseObject(JSON.
                toJSONString(request), Map.class)));
        List<ProductCheckResponse> value =null;
        if (jsonObject.containsKey("result")){  //判断 jsonObject 中是否存在result这个key
            if (jsonObject.getJSONArray("result")!=null){ //判断result中的key值是否为空
                value = jsonObject.getJSONArray("result").toJavaList(ProductCheckResponse.class);
            }
        }
        log.info("获取商品可售性结束，返回值"+value.toString());
        return value;
    }

    @Override
    public ProductAstricetResponse checkAreaLimit(ProductAastrictRequest request) {
        log.info("查询商品区域购买限制，请求参数："+request.toString());
        String url = this.url+"api/product/checkAreaLimit";
        JSONObject jsonObject = JSON.parseObject(JdVopHttpUtil.doRequestPost(url, JSON.parseObject(JSON.
                toJSONString(request), Map.class)));
        ProductAstricetResponse value =null;
        if (jsonObject.containsKey("result")){  //判断 jsonObject 中是否存在result这个key
            if (jsonObject.getJSONArray("result")!=null){ //判断result中的key值是否为空
                value = jsonObject.getJSONArray("result").toJavaObject(ProductAstricetResponse.class);
            }
        }
        log.info("查询商品区域购买限制，返回值"+jsonObject.toString());
        return null;
    }

    @Override
    public List<ProductGiftResponse> getSkuGift(ProductGiftRequest request) {
        String res = JdVopHttpUtil.doRequestPost(this.url + "api/product/getSkuGift", JSON.parseObject(JSON.toJSONString(request), Map.class));

        return null;
    }

    @Override
    public ProductGiftResponse getYanBao(ProductYanBaoRequest request) {
        String url  = this.url+"api/product/getYanbaoSku";
        return null;
    }

    @Override
    public Boolean getIsCod(ProductPaymentRequest request) {
        String url = this.url+"api/product/getIsCod";

        return null;
    }

    @Override
    public List<ProductSearchResponse> search(ProductSearchRequest request) {
        String url = this.url+"api/search/search";

        return null;
    }

    @Override
    public List<ProductSameParametersResponse> querySameParameters(ProductSimilarSkuRequest request) {
        String url = this.url+"api/search/getSimilarSku";
        return null;
    }

    @Override
    public List<ProductCategoryRestResponse> getCategory(ProductCategoryRequest request) {
        String url = this.url+"api/search/getCategory";
        return null;
    }

    @Override
    public List<ProductCategoryRestResponse> getCategorys(ProductCategorysRequest request) {
        String url = this.url+"api/search/getCategorys";
        return null;
    }


}
